package com.a9_lin.www.testormlite.dao;

import android.content.Context;

import com.a9_lin.www.testormlite.bean.UserInfoListBean;
import com.a9_lin.www.testormlite.bean.Userinfo;
import com.a9_lin.www.testormlite.bean.Watch;
import com.j256.ormlite.dao.Dao;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by macmini on 16/10/25.
 */

public class UserInfoListDao {

    private Context context;
    private Dao<UserInfoListBean,Integer> userDaoOpe;
    private DatabaseHelper helper;

    public UserInfoListDao(Context context){
        this.context = context;
        try{
            helper = DatabaseHelper.getHelper(context);
            userDaoOpe = helper.getDao(UserInfoListBean.class);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public void insert(UserInfoListBean userinfo){
        try{
            userDaoOpe.create(userinfo);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public boolean delete(UserInfoListBean userinfo){
        try{
             return userDaoOpe.delete(userinfo)==1;
        }catch (Exception e){
            e.printStackTrace();
        }
        return false;
    }

    public void update(UserInfoListBean userinfo){
        try{
            userDaoOpe.update(userinfo);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public List<UserInfoListBean> queryAll(){
        try{
            return userDaoOpe.queryForAll();
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }
    public UserInfoListBean query(int id){
        try{
            return userDaoOpe.queryForId(id);
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

    public List<UserInfoListBean> queryAllWithWatch(){
        try{
            List<UserInfoListBean> userinfos = userDaoOpe.queryForAll();
            for(int i = 0; i<userinfos.size();i++){
                UserInfoListBean userInfoListBean = userinfos.get(i);
                ArrayList<Userinfo> userinfos1 = new ArrayList<>(userInfoListBean.getUserinfos());
                for(int j = 0;j<userinfos1.size();j++){
                    helper.getDao(Userinfo.class).refresh(userinfos1.get(j));
                    helper.getDao(Watch.class).refresh(userinfos1.get(j).getWatch());
                }
            }
            return userinfos;
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

}
